package realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import realtime.app.func.BeanToJsonStrFunction;
import realtime.beans.TrafficBean;
import realtime.util.DateFormatUtil;
import realtime.util.DorisUtil;
import realtime.util.EnvUtil;
import realtime.util.KafkaUtil;

public class DwsTrafficWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = EnvUtil.getSEE(4);
        String topic = "dwd_traffic_page_log";
        String groupId = "dws_traffic_window_group";
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaConsumer(topic, groupId);
        DataStreamSource<String> kafkaStrDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");
        //转化为jsonobj
        SingleOutputStreamOperator<JSONObject> jsonObjDs = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(jsonStr);
                        out.collect(jsonObject);
                    }
                }
        );
        //指定水位线
        SingleOutputStreamOperator<JSONObject> watermarkDS = jsonObjDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject jsonObject, long l) {
                        return jsonObject.getLong("ts");
                    }
                }));
        //按照mid分组
        KeyedStream<JSONObject, String> keyedDS = watermarkDS.keyBy(v1 -> v1.getJSONObject("common").getString("mid"));
        //对数据进行处理并转化为实体类
        SingleOutputStreamOperator<TrafficBean> beanDS = keyedDS.process(
                new KeyedProcessFunction<String, JSONObject, TrafficBean>() {
                    private ValueState<String> lastVistDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastVistDateState", String.class);
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());
                        lastVistDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject jsonObj, KeyedProcessFunction<String, JSONObject, TrafficBean>.Context ctx, Collector<TrafficBean> out) throws Exception {
                        String lastVisitDate = lastVistDateState.value();
                        String sid = jsonObj.getJSONObject("common").getString("sid");
                        Long ts = jsonObj.getLong("ts");
                        String curDate = DateFormatUtil.toDate(ts);
                        Long uvCt = 0L;
                        if (StringUtils.isEmpty(lastVisitDate) || !lastVisitDate.equals(curDate)) {
                            uvCt = 1L;
                            lastVistDateState.update(curDate);
                        }
                        String lagePageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        Long sidCt = 0L;
                        //如果上一个页面为空 说明是新会话
                        if (StringUtils.isEmpty(lagePageId)) {
                            sidCt = 1L;
                        }
                        TrafficBean trafficBean = new TrafficBean(
                                "",
                                "",
                                "",
                                sid,
                                uvCt,
                                1L,
                                sidCt
                        );
                        out.collect(trafficBean);
                    }
                }
        );
        //按照会话分组
        KeyedStream<TrafficBean, String> sidKeyedDS = beanDS.keyBy(v1 -> v1.getSid());
        //开窗
        WindowedStream<TrafficBean, String, TimeWindow> windowDS = sidKeyedDS.window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)));
        //聚合
        SingleOutputStreamOperator<TrafficBean> reduceDS = windowDS.reduce(new ReduceFunction<TrafficBean>() {
                                                                             @Override
                                                                             public TrafficBean reduce(TrafficBean v1, TrafficBean v2) throws Exception {
                                                                                 v1.setPageCt(v1.getPageCt() + v2.getPageCt());
                                                                                 return v1;
                                                                             }
                                                                         },
                new WindowFunction<TrafficBean, TrafficBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TrafficBean> input, Collector<TrafficBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());

                        long timeMillis = System.currentTimeMillis();
                        String curDh = DateFormatUtil.toYmdH(timeMillis);
                        for (TrafficBean trafficBean : input) {
                            trafficBean.setStt(stt);
                            trafficBean.setEdt(edt);
                            trafficBean.setCurDh(curDh);
                            out.collect(trafficBean);
                        }
                    }
                }
        );
        //reduceDS.print(">>>>");
        reduceDS.map(new BeanToJsonStrFunction<>())
                .sinkTo(DorisUtil.getDorisSink("dws_traffic_hour_window"));

        env.execute();

    }
}
